import axios from 'axios';
import qs from 'qs';
import Vue from 'vue';

const http = axios.create({
  baseURL: window.SITE_CONFIG.baseUrl,
  timeout: 5000,
  withCredentials: true,
});
function judgeToken() {
  const url = window.location.href;
  let data = qs.parse(url.split('?')[1]);
  // sessionStorage.getItem('token');
  if (sessionStorage.getItem('token') && !data.token) {
    return false;
  } else {
    if (data.token) {
      sessionStorage.setItem('token', data.token);
      Vue.cookie.set('token', data.token);
    }
  }
}
// 添加请求拦截器
http.interceptors.request.use(
  (config) => {
    judgeToken();
    // 在发送请求之前设置token和浏览器标识
    config.headers['token'] = sessionStorage.getItem('token') || Vue.cookie.get('token'); // 请求头带上token
    // config.headers.token = Vue.cookie.get('token');
    config.headers.t = new Date().getTime();

    if (config.method === 'get') {
      // get请求对数组类型的参数进行处理
      config.paramsSerializer = (params) => {
        return qs.stringify(params, { arrayFormat: 'repeat' });
      };
    }

    return config;
  },
  (e) => {
    // 请求失败
    return Promise.reject(e);
  }
);

// 添加响应拦截器
http.interceptors.response.use(
  (response) => {
    // 文件下载
    if (response.data instanceof Blob) {
      return response;
    }
    // 响应数据处理
    if (response.data.code === 0) {
      return response.data;
    } else {
      return Promise.reject(response.data);
    }
  },
  (e) => {
    // 响应失败
    return Promise.reject(e);
  }
);

export default http;
